import click
import numpy as np
import matplotlib.pyplot as plt


@click.group()
def main():
    pass


@main.command()
@click.option('--count', default=100, type=int, help='Count of sample')
@click.option('--dof', default=3, type=int, help='Degree of freedom')
@click.option('--t', default=6.25, type=float)
@click.option('--show', default='false', type=bool, help='Whether to show chi-square')
def forward(count, dof, t, show):
    x_data = np.arange(count)
    y_data = np.random.normal(loc=0, scale=1, size=(count, dof))
    y_data = np.square(y_data)
    y_data = np.sum(y_data, axis=1)

    if show:
        plt.scatter(x_data, y_data)
        plt.show()

    count_nonzero = np.count_nonzero(y_data > t)
    print(1-count_nonzero/count)


@main.command()
@click.option('--count', default=100, type=int, help='Count of sample')
@click.option('--dof', default=3, type=int, help='Degree of freedom')
@click.option('--p', default=0.9, type=float)
@click.option('--show', default='false', type=bool, help='Whether to show chi-square')
def backward(count, dof, p, show):
    x_data = np.arange(count)
    y_data = np.random.normal(loc=0, scale=1, size=(count, dof))
    y_data = np.square(y_data)
    y_data = np.sum(y_data, axis=1)

    if show:
        plt.scatter(x_data, y_data)
        plt.show()

    for i in range(400000):
        temp = i*0.00005
        count_nonzero = np.count_nonzero(y_data > temp)
        probability = 1-count_nonzero/count
        if (np.abs(probability-p) < 0.0001):
            print(temp, probability)
            break


if __name__ == '__main__':
    main()
